package com.emuporium.gymrat.server.account;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.emuporium.gymrat.server.data.User;
import com.emuporium.gymrat.server.data.UserDB;

//Shamelessly stolen from Murach's Java Servlets and JSP 2nd Edition
@SuppressWarnings("serial")
public class AccountLoginServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String email = request.getParameter("email");
		String password = request.getParameter("password");

		// this user object is used elsewhere to determine if user is logged in
		User user = UserDB.selectUser(email);

//		HttpSession session = request.getSession();
//		session.setAttribute("user", user);

		String url = null;

		if (user == null) {
			request.setAttribute("message", "Bad email or password");
			url = "/account/login.jsp";
		} else {
//			session.setAttribute("message", "You are logged in");
			url = "/includes/redirect.jsp";
			request.setAttribute("redirecturl", "/home.jsp");
		}

		RequestDispatcher dispatcher = getServletContext()
				.getRequestDispatcher(url);
		dispatcher.forward(request, response);

	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}
}
